package com.shengzai

import scala.collection.immutable
import scala.io.Source

object Code41Example05 {
  def main(args: Array[String]): Unit = {

    //统计大于平均分的学生
    val score: List[String] = Source.fromFile("data/score.txt").getLines().toList

    //整理数据
    val groupBy: Map[String, List[(String, Int)]] = score.map(
      line => {
        val split: Array[String] = line.split(",")
        val id: String = split(0)
        val score: String = split(2)
        (id, score.toInt)
      }
      //根据学生分组
    ).groupBy(
      line => {
        line._1
      }
    )
    //计算总分最后只要总分，方便后续计算
    val resList: immutable.Iterable[Int] = groupBy.map(
      line => {
        var sum: Int = 0
        for (elem <- line._2) {
          sum += elem._2
        }
        sum
      }
    )
    //计算总分，并把学生号拿出来，为了结果
    val resList2: Map[String, Int] = groupBy.map(
      line => {
        var sum: Int = 0
        for (elem <- line._2) {
          sum += elem._2
        }
        (line._1, sum)
      }
    )
    //计算平均分
    val avgScore: Double = resList.sum.toDouble / resList.size
    //过滤掉小于平均分的学生
    val result: Map[String, Int] = resList2.filter(
      line => {
        line._2 > avgScore
      }
    )
    result.foreach(println)






  }

}
